package com.peoit.honeycomb.utils;

import org.springframework.web.context.ContextLoader;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.ServletContextResource;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.*;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * 上传工具
 * Created by wxzhou on 2014/11/4.
 */
public class UploadUtil {

    public static final String DEFAULT_UPLOAD_PATH = "/upload";
    public static final String URL_SEPARATOR = "/";



    public String  getUploadPicPath(MultipartFile files) {
        // 得到图片文件
        MultipartFile photoFile=null;
        String uploadFileName = "";
        try {
            photoFile = files;
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        if (photoFile.getOriginalFilename() != null && !photoFile.getOriginalFilename().equals("")) {
            try {
                // 保存后的文件
                File saveFile = uploadFileAndScale(photoFile);
                // 上传后的路径
                uploadFileName = UploadUtil.getWithDefaultPath(saveFile .getName());

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return uploadFileName;
    }


    protected File uploadFileAndScale(MultipartFile file) throws IOException {
        //上传原图
        File sourceImage = uploadFile(file);
        //处理原图
        Image image = ImageIO.read(sourceImage);
        String scaleImagePath = ScaleImageUtils.resize(image.getWidth(null), image.getHeight(null), ScaleImageUtils.ImageQuality.medium.getQuality(), sourceImage.getPath(), image);
        //返回处理后相同的路径
        return new File(scaleImagePath);
    }

    protected File uploadFile(MultipartFile file) throws IOException {
        String uploadFileExtensionName = UploadUtil.getExtensionName(file.getOriginalFilename());
        String uuid = UUID.randomUUID().toString();
        String fileName = new StringBuffer(uuid).append(".").append(uploadFileExtensionName).toString();
        String uploadFileFullPath = UploadUtil.getFileFullPath(fileName);
//        if (!uploadFileFullPath.endsWith(".jpg")||uploadFileFullPath.endsWith(".png")) {
//			throw new RuntimeException("请传入.jpg或.png结尾的文件");
//		}
        System.out.println("上传文件路径>>>>>>>>" + uploadFileFullPath);
        File uploadFile = new File(uploadFileFullPath);
        file.transferTo(uploadFile);
        return uploadFile;
    }



    /**
     * 获取上传路径
     *
     * @return
     */
    public static String getDefaultUploadPath() {
        WebApplicationContext webApplicationContext = ContextLoader.getCurrentWebApplicationContext();
        ServletContextResource UPLOAD_PATH = new ServletContextResource(webApplicationContext.getServletContext(), DEFAULT_UPLOAD_PATH);
        System.out.println("上传配置路径>>>>" + UPLOAD_PATH);
        try {
            return UPLOAD_PATH.getFile().getAbsolutePath();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 上传文件名+上传路径图
     * @param fileName
     * @return
     */
    public static String getWithDefaultPath(String fileName) {
        return DEFAULT_UPLOAD_PATH + URL_SEPARATOR + fileName;
    }

    /**
     * 获取文件全路径
     *
     * @param fileName
     * @return 返回文件物理路径
     */
    public static String getFileFullPath(String fileName) {
        return getDefaultUploadPath() + System.getProperty("file.separator") + fileName;
    }

    /**
     * 生成缩略图
     *
     * @param savePath         缩略图保存路径
     * @param originalFilePath 文件源路径
     * @return 缩略图路径
     * @throws Exception
     */
    private String generateScaleImage(String savePath, String originalFilePath) throws Exception {
        return ScaleImageUtils.resize(140, savePath, new File(originalFilePath));
    }

    /**
     * 生成缩略图
     *
     * @param targetFile 文件源路径
     * @return 缩略图路径
     * @throws Exception
     */
    public static String generateScaleImage(String targetFile) throws Exception {
        //获取随机的缩略图名
        String uploadScaleFilePath = getDefaultUploadPath() + System.getProperty("file.separator") + getId() + "." + getExtensionName(targetFile);
        return ScaleImageUtils.resize(140, uploadScaleFilePath, new File(targetFile));
    }

    /**
     * 根据上传的文件名进行MD5加密
     *
     * @param originalFilename
     * @return
     */
    public static String md5forFileName(String originalFilename) {
        return CipherUtil.encodeByMD5(originalFilename) + "." + getExtensionName(originalFilename);
    }

    /**
     * 获取一个随机生成的文件名，不带后缀
     * @return
     */
    public static String getRandomFileName() {
        return UUID.randomUUID().toString();
    }

    /**
     * 获取文件扩展名
     *
     * @param filename
     * @return
     */
    public static String getExtensionName(String filename) {
        if ((filename != null) && (filename.length() > 0)) {
            int dot = filename.lastIndexOf('.');
            if ((dot > -1) && (dot < (filename.length() - 1))) {
                return filename.substring(dot + 1);
            }
        }
        return filename;
    }

    /**
     * 获取不带扩展名的文件名
     *
     * @param filename
     * @return
     */
    public static String getFileNameNoEx(String filename) {
        if ((filename != null) && (filename.length() > 0)) {
            int dot = filename.lastIndexOf('.');
            if ((dot > -1) && (dot < (filename.length()))) {
                return filename.substring(0, dot);
            }
        }
        return filename;
    }

    /**
     * 获得UniqId
     */
    public static String getId() {
        String id = UUID.randomUUID().toString();
        id = id.replaceAll("-", "");
        return id;
    }

}
